<template>
  <!-- 轮播配置页面 -->
  <div>
    <!-- 头部 -->
    <div class="header">
      <el-button type="primary" @click="addCarouselData()">新增</el-button>
      <el-button type="success" @click="dialogVisible = true">预览</el-button>

      <el-select
        v-model="carouselStatus"
        clearable
        placeholder="请选择状态"
        style="margin-left: 10%"
      >
        <el-option label="正常" value="正常" />
        <el-option label="停用" value="停用" />
      </el-select>
      <el-button type="primary" @click="queryData()">查询</el-button>
    </div>
    <!-- 中间内容 -->
    <div class="main-content">
      <el-table :data="carouselData" style="width: 100%">
        <!-- 序号 -->
        <el-table-column type="index" label="序号" align="center" />

        <!-- 名称 -->
        <el-table-column prop="name" label="轮播图名称" align="center" />

        <!-- 轮播图描述 -->
        <el-table-column prop="introduce" label="轮播图描述" align="center" />

        <!-- 图片 -->
        <el-table-column prop="" label="轮播图图片" align="center">
          <template slot-scope="scope">
            <el-popover
              placement="right"
              width="250"
              heigth="500"
              trigger="hover"
            >
              <img
                :src="scope.row.url"
                style="
                  width: 150px;
                  heigth: 300px;
                  margin-left: 15%;
                  margin-top: 50px;
                  margin-bottom: 50px;
                "
              >
              <img
                slot="reference"
                :src="scope.row.url"
                style="max-height: 50px; max-width: 50px"
              >
            </el-popover>
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column prop="" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag
              size="mini"
              :type="scope.row.status == '正常' ? 'success' : 'danger'"
            >{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="warning"
              @click="editClick(scope.row)"
            >编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteData(scope.row)"
            >删除</el-button>
            <el-button
              size="small"
              :type="scope.row.status == '停用' ? 'success' : 'info'"
              @click="changeStatus(scope.row)"
            >
              <!-- 已经下架的话  就显示 上架 -->
              {{ scope.row.status == "停用" ? "启用" : "停用" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部 -->
    <div class="footer" />

    <!-- 预览模态框 -->
    <el-dialog title="大图预览" :visible.sync="dialogVisible" width="55%">
      <el-carousel :interval="3000" arrow="always">
        <el-carousel-item v-for="item in carouselData" :key="item.id">
          <img :src="item.url" style="width: 100%;height:100%;">
        </el-carousel-item>
      </el-carousel>

      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="dialogVisible = false"
        >关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 编辑 添加模态框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible2"
      width="55%"
      heigth="50%"
      :before-close="handleClose"
    >
      <div>
        <el-form
          ref="ruleForm"
          :model="carouselFormData"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="名称" prop="name">
            <el-input v-model="carouselFormData.name" />
          </el-form-item>

          <!-- 封面 -->
          <el-form-item label="轮播图片" prop="url">
            <el-upload
              class="avatar-uploader"
              :action="uploadFileURL"
              :show-file-list="false"
              :on-success="handleSuccess"
            >
              <img
                v-if="imageUrl"
                :src="carouselFormData.url"
                class="avatar"
              >
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>

          <el-form-item label="描述" prop="introduce">
            <el-input
              v-model="carouselFormData.introduce"
              type="textarea"
            />
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose()">取 消</el-button>
        <el-button type="primary" @click="dialogSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script src="/static/build/layui.js"></script>
<script>
import { post, get } from "../../../utils/request";
import { mapState, mapActions } from "vuex";

//引入文件上传路径 和· 文件预览路径
import { showFileURL, uploadFileURL } from "../../../utils/config";

export default {
  data() {
    return {
      // 状态
      carouselStatus: "",

      // 上传文件的服务器地址
      uploadFileURL,
      //
      imageUrl: "",
      //
      dialogVisible: false,
      dialogVisible2: false,
      //模态框标题
      dialogTitle: "",

      //轮播数据
      carouselData: [],
      //表单验证
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],

        // 封面
        url: [{ required: true, message: "请选择图片", trigger: "change" }],
      },

      //每条模态框 数据
      carouselFormData: {},
    };
  },
  computed: {},
  methods: {
    //查询按钮
    async queryData() {
      console.log(this.carouselStatus);
      if(this.carouselStatus == ''){
        this.getAllCarouselData();
      }else{
         let res = await get('/carousel/query',{status:this.carouselStatus})
         // console.log(res.data);

        this.carouselData = res.data;
      }

    },

    //新增按钮
    async addCarouselData() {
      //设置 模态框 标题
      this.dialogTitle = "新增轮播图";

      //打开模态框
      this.dialogVisible2 = true;

      //清空 原来carouselFormData表单数据
      this.carouselFormData = {};
      this.imageUrl = "";
    },

    //根据id 删除数据
    deleteData(res) {
      let flag = 1;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          flag = 0;
          let data = await get("/carousel/deleteById", { id: res.id });

          console.log(data);
          if (data.status == 200) {
            this.$message({
              type: "success",
              message: data.message,
            });
          } else {
            this.$message({
              type: "error",
              message: data.message,
            });
          }

          //重新加载全部数据
          this.getAllCarouselData();
        })
        .catch(() => {
          if (flag == 1) {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          }
        });
    },

    //改变状态
    async changeStatus(res) {
      if (res.status == "正常") {
        res.status = "停用";
      } else {
        res.status = "正常";
      }

      let data = await post("/carousel/saveOrUpdate", res);
      // 给用户一个成功的提示
      if (data.status == 200) {
        this.$message({
          message: data.message,
          type: "success",
        });
        //重新加载全部数据
        this.getAllCarouselData();
      } else {
        this.$message.error(data.message);
      }
    },

    async dialogSubmit() {
      console.log(this.carouselFormData);
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          //提交数据
          let res = await post("/carousel/saveOrUpdate", this.carouselFormData);
          console.log(res);
          // 给用户一个成功的提示
          if (res.status == 200) {
            this.$message({
              message: res.message,
              type: "success",
            });
            //关闭模态框 并清空表单数据
            this.dialogClose();
            //重新加载全部数据
            this.getAllCarouselData();
          } else {
            this.$message.error(res.message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    /**
     * @description: 上传成功之后 调用方法
     * @param {*} res 上传成功后回调的参数
     * @param {*} file 文件
     * @return {*}
     * @author: ZachGmy
     */
    handleSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl);
      // 上传成功之后 更新productForm.photo的路径+
      console.log(res);
      this.carouselFormData.url = showFileURL + res.data.id;
      // console.log(this.carouselFormData.url);
    },
    /**
     * @description: 上传之前 要做的一些限制
     * @param {*} file
     * @return {*}
     * @author: ZachGmy
     */
    // beforeUpload(file) {
    //   const isLt3M = file.size / 1024 / 1024 < 3;
    //   if (!isLt3M) {
    //     this.$message.error("上传头像图片大小不能超过 3MB!");
    //   }
    // },

    //编辑按钮
    editClick(res) {
      //设置模态框标题
      this.dialogTitle = "编辑轮播图";

      //打开模态框
      this.dialogVisible2 = true;

      //；把当前行的数据 赋值给data里的car....
      this.carouselFormData = { ...res };
      //
      this.imageUrl = this.carouselFormData.url;
    },

    //模态框关闭按钮
    handleClose(done) {
      this.$refs["ruleForm"].resetFields();
      done();
    },

    // 关闭模态框 调用表单重置的方法
    dialogClose() {
      // 重置表单
      this.$refs["ruleForm"].resetFields();
      // 关闭模态框
      setTimeout(() => {
        this.dialogVisible2 = false;
      }, 200);
    },

    //获取全部轮播数据
    async getAllCarouselData() {
      let res = await get("/carousel/findAll");
      // console.log(res);
      this.carouselData = res.data;
      console.log(this.carouselData);
    },
  },
  created() {
    this.getAllCarouselData();
  },
  mounted() {},
};
</script>

<style scoped>
.avatar{
   width: 100%;
   height: 180px;
}
</style>
